package root.electronclass.electronclass.home.widget;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;

import java.util.ArrayList;
import java.util.List;

import me.goldze.mvvmhabit.utils.KLog;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import root.electronclass.electronclass.common.base.BasicAdapter;
import root.electronclass.electronclass.common.base.BindingHolder;
import root.electronclass.electronclass.common.util.HeadUtil;
import root.electronclass.electronclass.databinding.HomeItemMessageBinding;
import root.electronclass.electronclass.databinding.HomeMessageInfoBinding;
import root.electronclass.electronclass.home.HomeFragment;
import root.electronclass.electronclass.mvp.GlobalParameter;
import root.electronclass.electronclass.mvp.base.BaseResponse;
import root.electronclass.electronclass.mvp.entity.HomeMsgInfoH;
import root.electronclass.electronclass.mvp.entity.HomeRowMsgInfoH;
import root.electronclass.electronclass.mvp.rest.RestManager;
import root.electronclass.electronclass.other.AttestationActivity;

public class HomeMsgView {
    private static final String TAG = "HomeMsgView";

    private static int requestCode = 0x1838;
    private static int requestCode1 = 0x1839;

    private HomeFragment context;
    private HomeMessageInfoBinding binding;

    private String curType;
    private List<String> typeList;


    {
        typeList = new ArrayList<>();
        typeList.add("老师");
        typeList.add("家长");
    }


    public HomeMsgView(HomeFragment context, ViewGroup view) {
        this.binding = HomeMessageInfoBinding.bind(view);
        this.context = context;
        init();
    }

    private void initViewPager(List<HomeMsgInfoH> list) {
        KLog.d("HomeMsgInfoH:" + list.size());
        List<View> views = new ArrayList<>();
        RecyclerView recyclerView = new RecyclerView(context.getContext());
        recyclerView.setLayoutManager(new LinearLayoutManager(context.getContext(), LinearLayoutManager.HORIZONTAL, false));

        BasicAdapter<HomeMsgInfoH, HomeItemMessageBinding> adapter = new BasicAdapter<HomeMsgInfoH, HomeItemMessageBinding>() {
            @Override
            public void onBindViewHolder(@NonNull BindingHolder<HomeItemMessageBinding> holder, @SuppressLint("RecyclerView") HomeMsgInfoH item) {
                holder.getBinding().ivStudName.setText(item.getName());
                holder.getBinding().ivMessageNum.setText(String.valueOf(item.getMsgUnReadCount()));
                if (item.getIcoUrlFormat() != null && !item.getIcoUrlFormat().isEmpty()) {
                    holder.getBinding().ivStudHeader.setImageURI(item.getIcoUrlFormat().get(0).getUrl());
                } else {
                    holder.getBinding().ivStudHeader.setActualImageResource(HeadUtil.getHeadPic(((int) (Math.random() * 2)) == 1 ? 0 : 1));
                }
                holder.getBinding().getRoot().setOnClickListener(v -> {
                    Intent intent = new Intent(context.getContext(), AttestationActivity.class);
                    context.startActivityForResult(intent, requestCode);
                });
            }

            @Override
            public void onBindViewHolder(@NonNull BindingHolder<HomeItemMessageBinding> holder, int position) {
                super.onBindViewHolder(holder, position);

            }
        };
        adapter.replaceAll(list);
        recyclerView.setTag(adapter);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        views.add(recyclerView);
//        }

        PagerAdapter pagerAdapter = new PagerAdapter() {
            @Override
            public int getCount() {
                return views == null ? 0 : views.size();
            }

            @Override
            public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
                return view == object;
            }

            @Override
            public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
                container.removeView(views.get(position));
            }

            @NonNull
            @Override
            public Object instantiateItem(@NonNull ViewGroup container, int position) {
                container.addView(views.get(position));
                return views.get(position);
            }
        };
        binding.viewPager.setAdapter(pagerAdapter);
    }

    private void init() {
        binding.tabSelector.initData(typeList);
        binding.tabSelector.setOnTabChangedListener(index -> request(String.valueOf(index + 2)));
        request("2");
    }

    public void refresh() {
        request(curType);
    }

    public void request(String type) {
        curType = type;
        long id = GlobalParameter.getEcardInfo().getClassId();

        RestManager.getInstance().initRest().messageList(type).enqueue(new Callback<BaseResponse<HomeRowMsgInfoH>>() {
            @Override
            public void onResponse(Call<BaseResponse<HomeRowMsgInfoH>> call, Response<BaseResponse<HomeRowMsgInfoH>> response) {
                if (!android.text.TextUtils.equals(type, curType)) {
                    return;
                }
                if (response.isSuccessful()
                        && response.body() != null
                        && response.body().getRows() != null
                        && response.body().getRows().getList() != null
                        && !response.body().getRows().getList().isEmpty()) {
                    Log.i(TAG, "onResponse: " + response.body().getRows().getList().size());
                    binding.viewPager.setVisibility(View.VISIBLE);
                    binding.imgEmpty.setVisibility(View.GONE);
                    binding.tvTips.setVisibility(View.VISIBLE);
                    List<HomeMsgInfoH> list = response.body().getRows().getList();
                    binding.tvTips.setText("以下" + list.size() + "位同学有新留言！");
                    initViewPager(list);
                } else {
                    binding.viewPager.setVisibility(View.GONE);
                    binding.imgEmpty.setVisibility(View.VISIBLE);
                    binding.tvTips.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailure(Call<BaseResponse<HomeRowMsgInfoH>> call, Throwable t) {

            }
        });
    }

    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == this.requestCode) {
            boolean result = data.getBooleanExtra("SUCCESS", false);
            if (resultCode == Activity.RESULT_OK && result) {
                //认证成功,跳转留言板
                Intent intent = new Intent(context.getContext(), MessageActivity.class);
                intent.putExtra("sendUserType", Integer.valueOf(curType));
                context.startActivityForResult(intent, this.requestCode1);
            } else {
                Toast.makeText(context.getContext(), "认证失败！", Toast.LENGTH_LONG).show();
            }
        }
        if (requestCode == this.requestCode1) {
            refresh();
        }

    }


}
